package com.util;

import com.sun.management.OperatingSystemMXBean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: cxt
 * @time: 2022/7/18
 * 监控系统：获取主机磁盘，内存信息
 */
@Slf4j
public class MonitorUtil {
    /**
     * 获取磁盘使用情况
     *
     * @return list
     */
    public static List<Disk> getDisk() {
        File[] files = File.listRoots();
        List<Disk> list = new ArrayList<>();
        for (File file : files) {
            String total = file.getTotalSpace() / 1024 / 1024 / 1024 + "G";
            String available = file.getUsableSpace() / 1024 / 1024 / 1024 + "G";
            list.add(new Disk(file.toString(), total, available));
        }
        return list;
    }

    /**
     * 获取内存信息
     *
     * @return map
     */
    public static Map<String, String> getMemory() {
        Map<String, String> map = new HashMap<>();
        // com.sun.management 包
        OperatingSystemMXBean systemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        String total = systemMXBean.getTotalPhysicalMemorySize() / 1024 / 1024 + "M";
        String remaining = systemMXBean.getFreePhysicalMemorySize() / 1024 / 1024 + "M";
        map.put("total", total);
        map.put("remaining", remaining);
        return map;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @ToString
    private static class Disk {
        // 磁盘名称
        private String name;

        // 空间大小
        private String totalSize;

        // 可用大小
        private String availableSize;
    }
}
